<?php

class KeywordController extends Zend_Controller_Action
{

    public function init()
    {
        $this->stylesBase = $this->view->baseUrl() . '/styles/';
    }
    
    public function indexAction()
    {         
        $view = $this->_getView('Promoties');  
        $keywords = $this->_getAllKeywords();  
        $view->keywords = $keywords;
        
       //ZendX_JQuery::enableView($view);
    }
    
    public function editAction()
    {   
        $view = $this->_getView('Edit keyword');
        $form = $this->_getEditKeywordForm();
        
        if ($this->getRequest()->isPost()) 
	{
            $formData  = $this->_request->getPost();
            if ($form->isValid($formData)) 
            {
                $view = $this->_getView('Fout - Toevoegen');  
                
                // Keyword toevoegen 
                $values = $form->getValues();

                $keyword_values['id'] = $values['keyword_id'];
                $keyword_values['label'] = $values['keyword_label'];
                $keyword_values['alternatives'] = $values['keyword_alternatives'];
                $keyword_values['shelfId'] = $values['keyword_shelf_id'];
       
                $keyword = new Application_Model_Keyword($keyword_values);
                
                $keywordMapper = new Application_Model_KeywordMapper();
                $keywordMapper->save($keyword);

                return $this->_helper->redirector('index', 'keyword');                
            }
        }else{
            $id = (string)$this->getRequest()->getParam('id');
            
            $keyword = $this->_getViewKeyword($id);
            //$keywords->
            if(isset($keyword))
            {
                $form->populate($keyword->toArray());         
            }            
            $view->form = $form; 
        }   
    }

    /**
     * @param string $title
     * @return Zend_View
     */
    private function _getView($title)
    {
        $view = $this->view;
        $view->title = $title;
        $view->headTitle($view->title, 'prepend');                           // Zend_View_Helper_HeadTitle
        $view->headLink()->appendStylesheet($this->stylesBase . 'main.css'); // Zend_View_Helper_HeadLink

        return $view;
    }
    
    private function _getEditKeywordForm()
    {   
        return new Application_Form_EditKeyword(array(
            'action' => $this->view->baseUrl() . '/keyword/edit/',
            'post'   => 'post',
        ));
    }
    
    /**
     * @return Array
     */
    private function _getAllKeywords()
    {
        $keywordMapper = new Application_Model_KeywordMapper();
        $keywordArray = $keywordMapper->fetchAll();

        return $keywordArray;
    }
    
    private function _getViewKeyword($id)
    {    
        $keywordMapper = new Application_Model_KeywordMapper();
        $keywordArray = $keywordMapper->fetchById($id);
        
        return $keywordArray;
    }
}

